package info.mrmt.apps.PeculiarBrowser;

import java.util.ArrayList;

import com.morimoto.rmlib.DrawElement;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class BrowserElement extends FrameLayout implements IBrowserElement {
	
	private WebView mWebView;
	
	private AsyncTask mAsyncTask;
	
	private LinearLayout mLoadingLayout = null;
	private boolean isLoading = false;
	private DrawElement mLoadingElement = null;
	
	

	private ArrayList<String> mHistoryList = null;

	public BrowserElement(Context context, int id, int width, int height) {
		super(context);
		LinearLayout baseLayout = new LinearLayout(context);
		baseLayout.setOrientation(LinearLayout.VERTICAL);
		addView(baseLayout);
		
		mWebView = new WebView(context);
		mWebView.setLayoutParams(new LayoutParams(width, Math.round(height * 0.8f)));
		baseLayout.addView(mWebView);
		
		mHistoryList = new ArrayList<String>();
		
		mAsyncTask = new AsyncTask<String, Integer, Long>() {
			@Override
			protected Long doInBackground(String... params) {
				return null;
			}
		};

		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setSupportMultipleWindows(true);
		mWebView.setWebViewClient(new Callback());
		
		LinearLayout controlLayout = new LinearLayout(context);
		controlLayout.setLayoutParams(new LayoutParams(width, Math.round(height * 0.2f)));
		controlLayout.setBackgroundColor(Color.DKGRAY);
		baseLayout.addView(controlLayout);
		
		Button button = new Button(context);
		button.setText("back");
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int num = mHistoryList.size();
				if (num >= 2) {
					mWebView.loadUrl(mHistoryList.get(num - 2));
					mHistoryList.remove(num - 1);
				}
			}
		});
		controlLayout.addView(button);
		
		button = new Button(context);
		button.setText("forward");
		controlLayout.addView(button);
	}

	public void setSize(int width, int height) {
		setLayoutParams(new android.widget.LinearLayout.LayoutParams(width, height));
	}

	public void loadUrl(String url) {
		mWebView.loadUrl(url);
	}

	public void reload() {
		mWebView.reload();
	}
	
	private class Callback extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			mHistoryList.add(url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
		}
	}
}
